# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "data.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read_csv(opt$g) %>%
  rename(ClassNote = Group) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

originalData <- read_csv(opt$i) %>%
  rename(Metabolite = SampleID)

data <- originalData %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID"))

numColumns <- colnames(data) %>%
  keep(function(x) {
    startsWith(x, "Nubmer") || startsWith(x, "Number")
  })

data <- data %>%
  mutate_at(vars(numColumns), as.numeric) %>%
  mutate_at(vars(-numColumns), factor)

data

getRoc <- function(name) {
  x <- data[name] %>%
    unlist() %>%
    as.ordered()
  y <- data$ClassNote
  rocRs <- roc(y, x, ci = T)
  return(list(name = name, roc = rocRs))
}

rocs <- originalData %>%
  .$Metabolite %>%
  unique() %>%
  map(getRoc)

print("===")

aucData <- rocs %>%
  map_dfr(function(rocList) {
    rocRs <- rocList$roc
    name <- rocList$name
    auc <- round(rocRs$auc, 3)
    ci <- rocRs$ci
    ci1 <- ci[1]
    ci2 <- ci[3]
    pointData <- coords(rocRs, "best", transpose = T) %>%
      round(3) %>%
      as.data.frame() %>%
      rownames_to_column("Name") %>%
      select(1:2) %>%
      gather("Kind", "Value", -Name) %>%
      spread(Name, "Value")
    return(data.frame(Metabolite = name, AUC = auc, CI1 = ci1, CI2 = ci2, Thres = pointData$threshold,
                      Specificity = pointData$specificity, Sensitivity = pointData$sensitivity))
  }) %>%
  arrange(desc(AUC)) %>%
  rename(Var = Metabolite)

aucData

outFileName <- "Single_Var_ROC.csv"
write.csv(aucData, outFileName, row.names = F)









